package com.cy.pj.ajax.controller;

import org.springframework.web.bind.annotation.*;

import java.util.*;


@RestController
public class AjaxController {
    private List<Map<String, String>> dbList = new ArrayList<>();
    public AjaxController() {
        Map<String, String> map = new HashMap<>();
        map.put("id", "100");
        map.put("name", "家用电器");
        map.put("parentId", null);
        map.put("remark", "beijing");

        dbList.add(map);
        map = new HashMap<>();
        map.put("id", "10");
        map.put("name", "家用");
        map.put("parentId", null);
        map.put("remark", "shanghai");

        dbList.add(map);
   }
    //接收post请求方式json格式数据
    @PostMapping("/doAjaxPostJSON")
    public String doSaveJsonObject(@RequestBody Map<String,String> map){
        dbList.add(map);
        return "save json ok";
    }
    @GetMapping(path={"/doAjaxGet/{remark} ","/doAjaxGet"})
    //@ResponseBody
    public  List<Map<String, String>> doAjaxGet(@PathVariable(required = false) String remark){
        if(remark==null||"".equals(remark)) return dbList;
      List<Map<String, String>> queryResult= new ArrayList<>();//基于此集合储存查询结果
        for (Map<String, String> map:dbList) {
            if(map.get("remark").contains("s")){
            queryResult.add(map);}
        }
        return queryResult;

    }
//    @GetMapping("/doAjaxGet")
//    //@ResponseBody
//    public  List<Map<String, String>> doAjaxGet(){
//
//        return  dbList;
//    }

    @PostMapping("/doAjaxPost")
    public String doAjaxPost(Map<String, String> map){
       dbList.add(map);
        return "save ok";
    }

    //通过ajax方法发送get请求，访问此方法
    //方法的返回值要在页面上通过局部刷新的方式进行实现
    @GetMapping("/doAjaxStart")
    public String doAjaxStart() {
        return "Response Result Of Ajax Get Request 01 ";
    }
    @DeleteMapping("/doAjaxDelete/{id}")
    public  String doDeleteObject(@PathVariable String id){
//        for (Map<String, String> map:dbList) {
//            if(map.get("id").equals(id)){
//                dbList.remove(map);//在迭代的时候不允许直接删除
//            }
//        }
            //基于迭代器执行删除操作
        Iterator<Map<String, String>> it = dbList.iterator();
        while(it.hasNext()){
            Map<String, String> map = it.next();
            if(map.get("id").equals(id)){
                it.remove();//基于迭代器执行删除操作
            }
        }
        return  "delete ok";
    }
@PutMapping("/doAjaxPut")
    public  String doUpdateObject(@RequestParam Map<String, String> paramMap ) {
        String id = paramMap.get("id");
        Iterator<Map<String, String>> it = dbList.iterator();
        while (it.hasNext()) {
            Map<String, String> map = it.next();
            if (map.get("id").equals(id)) {
                map.put("remark", paramMap.get("remark"));
            }

        }
        return "update ok";
    }

}
